<template>
  <div class="login">
    <div class="logo">
      <img src="@/assets/logo.png" alt="logo" />
    </div>
  <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      status-icon
      :rules="rules"
      class="demo-ruleForm"
  >

    <el-form-item label="邮箱" prop="email">
      <el-input v-model="ruleForm.email" type="text" autocomplete="off" />
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="ruleForm.password" type="password" autocomplete="off" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)"
      >登录</el-button
      >
      <el-button @click="resetForm(ruleFormRef)">清除</el-button>
    </el-form-item>
  </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { authApi } from "@/apis/auth"
import { useAuthStore } from '@/stores/index'
import { useRouter} from 'vue-router'
import { h } from 'vue'
import { ElNotification } from 'element-plus'
const router = useRouter()
const authStore = useAuthStore()

defineOptions({
  name: "LoginView"
})
const ruleFormRef = ref<FormInstance>()

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('密码不能为空'))
  } else {
    // if (ruleForm.checkPass !== '') {
    //   if (!ruleFormRef.value) return
    //   ruleFormRef.value.validateField('checkPass', () => null)
    // }
    callback()
  }
}

const ruleForm = reactive({
  password: '',
  email:''
})

const rules = reactive<FormRules<typeof ruleForm>>({
  password: [{ required: true, validator: validatePass, trigger: 'blur' }],
  email: [{ required: true, type: 'email', message: "请输入正确的邮箱" , trigger: 'blur' }]
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      HandleLogin({ email: ruleForm.email, password: ruleForm.password})
    } else {
      console.log('error submit!')
      return false
    }
  })
}


const HandleLogin = async (data: LoginData) => {
  const res = await authApi(data)
  authStore.setToken(res.data.token)
  authStore.setAudioToken(res.data['audio-token'])
  ElNotification({
    title: '登录结果',
    message: h('i', { style: 'color: teal' }, '登陆成功'),
  })
  await router.push('/')
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<style lang="scss" scoped>
.login{
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  .logo img{
    width: 150px;
    height: 150px;
    margin-bottom: 30px;
  }

}
</style>